package cn.com.utt.unms.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.com.utt.common.http.Client;
import cn.com.utt.common.util.DesUtil;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.pojo.Province;
import cn.com.utt.unms.pojo.Wireless;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.NetworkService;
import cn.com.utt.unms.service.UserRecordService;
import cn.com.utt.unms.service.WirelessService;
import cn.com.utt.unms.vo.DeviceInfo;
import cn.com.utt.unms.vo.GraphQueryResponse;
import cn.com.utt.unms.vo.OnlineUser;
import cn.com.utt.unms.vo.SimpleDevice;
import cn.com.utt.unms.vo.SoftVersion;

@RestController
@RequestMapping("v1/devices")
public class DeviceController {
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private UserRecordService userRecordService;

	@Autowired
	private WirelessService wirelessService;

	@Autowired
	private NetworkService networkService;

	@PreAuthorize("hasRole('DEVICE_VIEW')")
	@RequestMapping(value = "/search", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> queryDevice(@RequestBody TableInput input, Principal principal, HttpServletRequest request, HttpServletResponse response) {
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		String serverName = request.getServerName();
		boolean flag = false;
		if (serverName.equals("cloud.transliteglobal.com") || serverName.equals("cloud.uttglobal.com")){
			flag = false;
		}else{
			flag = true;
		}
		TableOutput<DeviceInfo> output = deviceService.queryByCondition(input, user.getGroupId(), flag);
		RestResult result = new RestResult();
		result.put("start", output.getStart());
		result.put("rows", output.getRows());
		result.put("total", output.getTotal());
		result.put("devices", output.getList());
		if (user.hasRole("ROLE_DEVICE_EDIT")) {
			result.put("hasEditRole", true);
		} else {
			result.put("hasEditRole", false);
		}
		return result.toJsonObject();
	}

	/**
	 * 检测序列号与验证码是否匹配
	 * 
	 * @param code
	 * @param sn
	 * @return
	 */
	@RequestMapping(value = "/checksc", method = { RequestMethod.POST })
	public Map<String, Object> querySnCode(String code, String sn) {
		RestResult result = new RestResult();
		if (code == null || sn == null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.SnOrCodeNotNull));
			return result.toJsonObject();
		}
		DesUtil desUtil1 = new DesUtil(sn,1);
		DesUtil desUtil2 = new DesUtil(sn,2);
		String mistr1 = desUtil1.getEncString(sn,1);
		String mistr2 = desUtil2.getEncString(sn,2);
		if (!(mistr1.startsWith(code)) && !(mistr2.startsWith(code))) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.SnCodeNoMatch));
			return result.toJsonObject();
		}
		return result.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/import", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> singleImport(@RequestBody Device device) {

		RestResult result = deviceService.isRightFormate(device);
		if (result.getErrorCode() != 0) {
			String[] msg = result.getErrorMsg().split(":");
			if (result.getErrorCode() == 11) {
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.SnCodeNoMatch));
			} else {
				result.setErrorMsg(msg[1]);
			}
			return result.toJsonObject();
		}
		Device temp = null;
		if(device.getImportType() == 1){
			temp = deviceService.queryDeviceBySn(device.getSn());
		}
		if (temp != null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceBeBinded));
			return result.toJsonObject();
		}
		RestResult tempres=deviceService.save(device);
		result.put("deviceId", tempres.toJsonObject().get("deviceId"));
		result.setErrorMsg(messageSourceUtil.getMessage(Tips.BindSuccess));
		return result.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/batch/import", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> batchImport(@RequestParam("file") MultipartFile file,
			@RequestParam("networkId") long networkId,@RequestParam("type") int type,  Principal principal) {

		RestResult result = deviceService.writeFileToDisk(file, "excel");
		if (result.getErrorCode() != 0) {
			return result.toJsonObject();
		}
		String filename = result.getErrorMsg();

		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();

		File f = new File(filename);
		RestResult res = deviceService.readExcelAndBindDevice(f, networkId, user.getGroupId(), type);
		return res.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_VIEW')")
	@RequestMapping(value = "/export", method = { RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> export(Principal principal,HttpServletRequest request, HttpServletResponse response) {
		
		if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
			return null;
		}

		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		List<Device> devices = deviceService.queryChildrenDevicesByGroupId(user.getGroupId());

		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建HSSFSheet对象
		HSSFSheet sheet = wb.createSheet(messageSourceUtil.getMessage(Tips.DeviceInfo));
		sheet.setColumnWidth(4, 10 * 400);
		sheet.setColumnWidth(1, 10 * 256);
		// 创建HSSFRow对象
		HSSFRow row = sheet.createRow(0);
		// 创建HSSFCell对象
		row.createCell(0).setCellValue(messageSourceUtil.getMessage(Tips.SN));
		row.createCell(1).setCellValue(messageSourceUtil.getMessage(Tips.ActivationCode));
		row.createCell(2).setCellValue(messageSourceUtil.getMessage(Tips.Model));
		row.createCell(3).setCellValue(messageSourceUtil.getMessage(Tips.FirmwareVersion));
		row.createCell(4).setCellValue(messageSourceUtil.getMessage(Tips.HardwareVersion));

		int i = 1;
		for (Device device : devices) {
			row = sheet.createRow(i);
			row.createCell(0).setCellValue(device.getSn());
			row.createCell(1).setCellValue(device.getCode());
			row.createCell(2).setCellValue(device.getModel());
			row.createCell(3).setCellValue(device.getSoftVer());
			row.createCell(4).setCellValue(device.getHardwareVer());
			i++;
		}

		OutputStream out = null;
		String filename = messageSourceUtil.getMessage(Tips.DeviceInfo);
		try {
			out = response.getOutputStream();
			response.setContentType("application/ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=".concat(String.valueOf(URLEncoder.encode(filename + ".xls", "UTF-8"))));
			wb.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;

	}

	@RequestMapping(value = "/download", method = { RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> download(HttpServletRequest request, HttpServletResponse response, int type) {
		RestResult res = new RestResult();
		ServletOutputStream outs = null;
		BufferedInputStream br = null;
		try {
			String filename = "";
			if(type == 1){//sn
				filename = "batch_import1.xlsx";
				filename = java.net.URLEncoder.encode(filename, "UTF-8");
			}else if(type == 2){//防伪码
				filename = "batch_import2.xlsx";
				filename = java.net.URLEncoder.encode(filename, "UTF-8");
			}
			String filelocation = "excels";
			String filesavename = messageSourceUtil.getMessage(Tips.ImportDeviceTemplate) + ".xlsx";
			filesavename = java.net.URLEncoder.encode(filesavename, "UTF-8");
			// 可以修改成其他路径
			String rootPath = System.getProperty("user.dir");
			File file = new File(rootPath + File.separator + filelocation + File.separator + filename);
			System.out.println(System.getProperty("user.dir"));
			// 判断文件是否存在
			if (file.exists() && file.isFile()) {
				FileInputStream fis = new FileInputStream(
						rootPath + File.separator + filelocation + File.separator + filename);
				outs = response.getOutputStream();
				response.reset();
				response.setContentType("APPLICATION/OCTET-STREAM");
				response.setContentType("application/x-msdownload");
				response.setHeader("Content-Disposition", "attachment; filename=\"" + filesavename + "\"");
				br = new BufferedInputStream(fis);
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = br.read(buf)) > 0) {
					outs.write(buf, 0, len);
				}
			} else {
				res.setErrorCode(-1);
				res.setErrorMsg(messageSourceUtil.getMessage(Tips.FileDoesNotExist));
			}
		} catch (Exception e) {
			res.setErrorCode(-1);
			res.setErrorMsg(messageSourceUtil.getMessage(Tips.FailedToDownloadTheTemplate));
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outs != null) {
				try {
					outs.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					outs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return res.toJsonObject();
	}

	/**
	 * 设备基本配置--update
	 * 
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "update", method = { RequestMethod.POST })
	public Map<String, Object> updateDevice(Long deviceId, Long networkId, String deviceName, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (networkId == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		if (deviceId == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		if (deviceName.length() != 0 && deviceName.trim().length() == 0) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceNameNotAllSpace));
			return result.toJsonObject();
		}
		if (deviceName.length() > 64) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceNameNotGreaterThan64Letters));
			return result.toJsonObject();
		}
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (deviceName.length() == 0) {
			deviceName = device.getMac();
		}
		long oldNid = device.getNetworkId();
		device.setNetworkId(Math.abs(networkId.longValue()));
		device.setName(deviceName.trim());
		deviceService.update(device);
		result.setErrorMsg(messageSourceUtil.getMessage(Tips.OperationSucceed));
		if (oldNid != Math.abs(networkId.longValue())) {
			List<Device> devices = new ArrayList<>();
			devices.add(device);
			List<Wireless> wirelesses = wirelessService.queryWirelessesByNetwork(networkId);
			if (wirelesses.size() == 1
					&& (wirelesses.get(0) == null || wirelesses.get(0).getName().equals("default"))) {
				wirelesses = null;
			}
			result = deviceService.updateDeviceWireless(devices, wirelesses, true);
			if (result.getErrorCode() != 0) {
				return result.toJsonObject();
			}
			if (device.getSystemMode() == 1) {// 胖ap模式
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.ConfigSuccess));
			} else {
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.OperationSucceed));
			}
		}

		return result.toJsonObject();
	}

	/**
	 * 设备重启(暂不用)
	 * 
	 * @param deviceid
	 * @param userid
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "restarts", method = { RequestMethod.POST })
	public Map<String, Object> rebootDevice(Long deviceId, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		System.out.println("deviceId: "+deviceId);
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (device.getStatus() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceOffline));
			return result.toJsonObject();
		}
		if (device.getName() == null || device.getName() == "" || device.getName().length() == 0) {
			device.setName(device.getMac());
		}
		if (deviceService.restart(device).getErrorCode() == 0) {
			result.setErrorCode(0);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.RestartCmdSuccess));
		} else {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.RestartCmdFail));
		}
		return result.toJsonObject();

	}
	
	/**
	 * 设备批量重启
	 * @param deviceIds
	 * @param principal
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "restart", method = { RequestMethod.POST })
	public Map<String, Object> rebootDevices(@RequestParam(value = "deviceId[]") List<Long> deviceIds, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (deviceIds == null || deviceIds.size() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		List<Device> devices = deviceService.queryDeviceByIds(deviceIds);
		if (devices.size()<=0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (!deviceService.hasRights(devices, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		result=deviceService.restarts(devices);
		return result.toJsonObject();

	}
	
	/**
	 * 设备批量重启
	 * @param deviceIds
	 * @param principal
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "reset", method = { RequestMethod.POST })
	public Map<String, Object> resetDevices(@RequestParam(value = "deviceId[]") List<Long> deviceIds, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (deviceIds == null || deviceIds.size() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		List<Device> devices = deviceService.queryDeviceByIds(deviceIds);
		if (devices.size()<=0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (!deviceService.hasRights(devices, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		result=deviceService.reset(devices);
		deviceService.unbind(devices);
		return result.toJsonObject();

	}
	
	


	/*
	 * /searchByGroup/1/history?start=133999990&end=1938339339
	 */
	@RequestMapping(value = "/searchByNetwork/{networkId}/history", method = { RequestMethod.GET })
	public Map<String, Object> searchHistoryByNetwork(@PathVariable Long networkId, Long start, Long end, Byte type,
			Byte shape, Integer range, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (networkId == null || networkId <= 0) {
			result.setErrorCode(-1);
			result.setErrorMsg("networkId is required");
			return result.toJsonObject();
		}
		if (shape == 2) {// 折线图
			if (start == null || start <= 0) {
				result.setErrorCode(-1);
				result.setErrorMsg("start time is required");
				return result.toJsonObject();
			}
			if (end == null || end <= 0) {
				result.setErrorCode(-1);
				result.setErrorMsg("end time is required");
				return result.toJsonObject();
			}
		}
		if (!networkService.hasRight(user.getGroupId(), new ArrayList<Long>() {
			{
				add(networkId);
			}
		})) {
			// 没有权限
			result.setErrorCode(-1);
			result.setErrorMsg("network has no right");
			return result.toJsonObject();
		}

		Object datas = deviceService.queryHistoryByNetwork(user.getId(), networkId, start / 1000, end / 1000, type,
				shape, range);
		result.put("datas", datas);
		return result.toJsonObject();
	}

	/**
	 * 远程连接
	 * 
	 * @param deviceid
	 * @param userid
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "remoteConnect", method = { RequestMethod.POST })
	public Map<String, Object> remoteConnect(Long deviceId,String webport,HttpServletRequest request, HttpServletResponse response, Principal principal) {
		String serverName = request.getServerName();
		String host = "tunnel.uttglobal.com";
		if (serverName.equals("cloud.transliteglobal.com")){
			host = "tunnel.transliteglobal.com";
		}else if (serverName.equals("cloud.anphat.vn")){
			host = "tunnel.anphat.vn";
		}
		// 1、判断用户对设备是否有管理权限
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		RestResult result = new RestResult();
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (device.getStatus() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceOffline));
			return result.toJsonObject();
		}
		deviceService.remoteConnect(device.getSn(),webport,host);
		return result.toJsonObject();
	}

	/**
	 * 远程管理
	 * 
	 * @param deviceId
	 * @param session
	 * @return
	 */
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "remoteWebStatus", method = { RequestMethod.POST })
	public Map<String, Object> remoteWebStatus(Long deviceId,HttpServletRequest request, HttpServletResponse response, Principal principal) {
		String serverName = request.getServerName();
		String host = "tunnel.uttglobal.com";
		if (serverName.equals("cloud.transliteglobal.com")){
			host = "tunnel.transliteglobal.com";
		}else if (serverName.equals("cloud.anphat.vn")){
			host = "tunnel.anphat.vn";
		}
		// 1、判断用户对设备是否有管理权限
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		RestResult result = new RestResult();
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		if (device.getStatus() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceOffline));
			return result.toJsonObject();
		}
		Map<String, Object> res = deviceService.remoteWebStatus(device.getSn(),host);
		System.out.println("=====remoteWebStatus=====");
		System.out.println(JSON.toJSONString(res));
		if (res == null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.RemoteConnectFail));
			return result.toJsonObject();
		}
		if (res.get("errorCode") != null && !res.get("errorCode").toString().equals("0")) {
			return res;
		}
		int status = 0;
		URL url;
		HttpURLConnection conn = null; 
		try {
			url = new URL(res.get("portforward").toString());
			conn = (HttpURLConnection) url.openConnection();  
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
            conn.setRequestMethod("HEAD"); 
            try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            status = conn.getResponseCode();
		} catch (IOException e) { 
			e.printStackTrace();
            status = 0;  
        } finally {  
           conn.disconnect();  
      }  
	         
	    if (status != 200 && status != 302){
	    		result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.RemoteConnectFail));
			return result.toJsonObject();
	    }
		result.put("portforward", res.get("portforward"));
		return result.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/unbind", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> unbind(@RequestParam(value = "deviceId[]") List<Long> deviceIds, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (deviceIds == null || deviceIds.size() == 0) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		List<Device> devices = deviceService.queryDeviceByIds(deviceIds);
		if (!deviceService.hasRights(devices, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		deviceService.unbind(devices);
		result.setErrorMsg(messageSourceUtil.getMessage(Tips.UnbindSuccess));
		return result.toJsonObject();
	}
	
	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/switchfast", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> switchFast(@RequestParam(value = "deviceId[]") List<Long> deviceIds,Byte isFast, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (deviceIds == null || deviceIds.size() == 0 || isFast == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		List<Device> devices = deviceService.queryDeviceByIds(deviceIds);
		if (!deviceService.hasRights(devices, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		deviceService.switchFast(devices,isFast);
		result.setErrorMsg(messageSourceUtil.getMessage(Tips.OperationSucceed));
		return result.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/batch/updateSV", method = { RequestMethod.POST }, consumes = "application/json")
	@ResponseBody
	public Map<String, Object> batchUpdateSV(@RequestBody List<SoftVersion> svs, Principal principal) {
		RestResult result;
		System.out.println(JSON.toJSONString(svs));
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		result = deviceService.batchUpdateSV(svs, user.getId(), user.getGroupId());
		return result.toJsonObject();
	}

	/*
	 * 用户状态:在线用户
	 */
	@PreAuthorize("hasRole('USER_VIEW')")
	@RequestMapping(value = "/onlineUser", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> onlineUser(@RequestBody TableInput input, Principal principal) {
		System.out.println(JSON.toJSONString(input));
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		TableOutput<OnlineUser> output = userRecordService.queryUserByCondition(input, user.getId(), user.getGroupId());
		RestResult result = new RestResult();
		result.put("start", output.getStart());
		result.put("rows", output.getRows());
		result.put("total", output.getTotal());
		result.put("devices", output.getList());
		if (user.hasRole("ROLE_USER_EDIT")) {
			result.put("hasEditRole", true);
		} else {
			result.put("hasEditRole", false);
		}
		return result.toJsonObject();
	}

	/*
	 * 用户状态:历史用户
	 */
	@PreAuthorize("hasRole('USER_VIEW')")
	@RequestMapping(value = "/historyUser", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> historyUser(@RequestBody TableInput input, Principal principal) {
		System.out.println(JSON.toJSONString(input));
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		TableOutput<OnlineUser> output = userRecordService.queryUserByCondition(input, user.getId(), user.getGroupId());
		RestResult result = new RestResult();
		result.put("start", output.getStart());
		result.put("rows", output.getRows());
		result.put("total", output.getTotal());
		result.put("devices", output.getList());
		if (user.hasRole("ROLE_USER_EDIT")) {
			result.put("hasEditRole", true);
		} else {
			result.put("hasEditRole", false);
		}
		return result.toJsonObject();
	}

	@RequestMapping(value = "/simplelist", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> simplelist(Principal principal) {
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		List<Device> allDevices = deviceService.queryChildrenDevicesByGroupId(user.getGroupId());
		RestResult result = new RestResult();
		List<SimpleDevice> simples = new ArrayList<>();
		for (Device device : allDevices) {
			SimpleDevice simple = new SimpleDevice();
			simple.convert(device);
			simples.add(simple);
		}
		result.put("allDevices", simples);
		return result.toJsonObject();
	}

	/**
	 * 设备详情-信息：概要
	 * 
	 * @param device
	 * @param principal
	 * @return
	 */

	@RequestMapping(value = "general", method = { RequestMethod.POST })
	public Map<String, Object> generalInfo(Long deviceId, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		JSONObject res = deviceService.general(device);
		if (res == null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.Error));
			return result.toJsonObject();
		}
		if(device.getType().equals("1") || device.getType().equals("1.1")){
			result.put("system", res.get("system"));
		}else{
			result.put("system", res.get("system"));
			result.put("net", res.get("net"));
		}
		return result.toJsonObject();
	}

//	@PreAuthorize("hasRole('DEVICE_EDIT')")
//	@RequestMapping(value = "reset", method = { RequestMethod.POST })
//	public Map<String, Object> reset(Long deviceId, Principal principal) {
//		RestResult result = new RestResult();
//		Authentication authentication = (Authentication) principal;
//		User user = (User) authentication.getPrincipal();
//		Device device = deviceService.queryDeviceById(deviceId);
//		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
//			result.setErrorCode(-1);
//			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
//			return result.toJsonObject();
//		}
//		if (device.getStatus() == 0) {
//			result.setErrorCode(-1);
//			result.setErrorMsg(messageSourceUtil.getMessage(Tips.DeviceOffline));
//			return result.toJsonObject();
//		}
//		if (deviceService.reset(device)) {
//			result.setErrorMsg(messageSourceUtil.getMessage(Tips.ResetDeviceSuccess));
//		} else {
//			result.setErrorMsg(messageSourceUtil.getMessage(Tips.ResetDeviceFail));
//		}
//		return result.toJsonObject();
//	}

	/**
	 * Ap24小时客流统计
	 * 
	 * @param principal
	 * @param deviceId
	 * @param start
	 * @param end
	 * @return
	 */
	@RequestMapping(value = "visitorsRT", method = { RequestMethod.POST })
	public Map<String, Object> visitorsRealTimeData(Principal principal, Long deviceId, Long start, Long end) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		List<GraphQueryResponse> resps = deviceService.visitorsRealTimeData(device.getSn(), device.getBindTime(), start,
				end);
		result.put("datas", resps);
		return result.toJsonObject();
	}

	@PreAuthorize("hasRole('DEVICE_EDIT')")
	@RequestMapping(value = "/updateSV", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateSV(@RequestParam("file") MultipartFile file,
			@RequestParam("deviceId") Long deviceId, Principal principal, HttpServletRequest request) {
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		RestResult result = new RestResult();
		Device device = deviceService.queryDeviceById(deviceId);
		if (deviceId == null || device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		result = deviceService.writeFileToDisk(file, "software");
		if (result.getErrorCode() != 0) {
			return result.toJsonObject();
		}
		String filename = result.getErrorMsg();
		String url = request.getScheme() + "://" + request.getServerName() + "/" + filename;
		Map<Long, String> svs = new HashMap<>();
		svs.put(deviceId, url);
		return null;
	}

	/**
	 * 实时数据统计：1小时丢包统计
	 * 
	 * @param principal
	 * @param deviceId
	 * @param start
	 * @param end
	 * @return
	 */
	@RequestMapping(value = "lossPack", method = { RequestMethod.POST })
	public Map<String, Object> OneHourPackageLoss(Principal principal, Long deviceId, Long start, Long end) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (!deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		List<GraphQueryResponse> res = deviceService.packLoss(device.getSn(), start, end);
		result.put("datas", res);
		return result.toJsonObject();
	}

	/**
	 * 实时数据统计：1小时错包统计
	 * 
	 * @param principal
	 * @param deviceId
	 * @param start
	 * @param end
	 * @return
	 */
	@RequestMapping(value = "errorPack", method = { RequestMethod.POST })
	public Map<String, Object> OneHourPackageError(Principal principal, Long deviceId, Long start, Long end) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (!deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		List<GraphQueryResponse> res = deviceService.packError(device.getSn(), start, end);
		result.put("datas", res);
		return result.toJsonObject();
	}

	/**
	 * 流量统计
	 * 
	 * @param principal
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "flowStatistics", method = { RequestMethod.POST })
	public Map<String, Object> flowStatistics(Principal principal, Long networkId) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		if (user == null || networkId == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		Map<String, Object> res = deviceService.flowStatistics(user.getId(), networkId);
		result.put("datas", res);
		return result.toJsonObject();
	}

	@RequestMapping(value = "/checksv", method = { RequestMethod.GET })
	public Map<String, Object> checksv(String softVer) {
		RestResult result = new RestResult();
		String bt = softVer.substring(softVer.lastIndexOf("-") + 1);
		softVer = softVer.substring(0,softVer.lastIndexOf("-"));
		
		String sv = softVer.substring(softVer.lastIndexOf("v") + 1);
		String st = softVer.substring(0,softVer.lastIndexOf("v"));
		Client client = new Client();
		String soft = client.doPostWithJson("http://rjsj.utt.com.cn/softUpdateCheck.php?st="+st+"&sv="+sv+"&bt="+bt+"&ver=2", "");
		result.put("data", soft);
		return result.toJsonObject();
	}
	 /**
	  * 无限拓展
	  * @param deviceId
	  * @param principal
	  * @return
	  */
	@RequestMapping(value = "wirelessExpansion", method = { RequestMethod.POST })
	public Map<String, Object> wirelessExpansion(Long deviceId, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		JSONObject res = deviceService.wirelessExpansion(device);
		if (res == null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.Error));
			return result.toJsonObject();
		}
		result.put("data", res);
		return result.toJsonObject();
	}
	/**
	 * 无限拓展-批量管理：射频、网络配置信息获取
	 * @param deviceId
	 * @param principal
	 * @return
	 */
	@RequestMapping(value = "batchRfAndServiceZone", method = { RequestMethod.POST })
	public Map<String, Object> batchRfAndServiceZone(Long deviceId, Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		Device device = deviceService.queryDeviceById(deviceId);
		if (device == null || !deviceService.hasRight(device, user.getGroupId())) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PermissionDenied));
			return result.toJsonObject();
		}
		JSONObject res = deviceService.batchRfAndServiceZone(device);
		if (res == null) {
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.Error));
			return result.toJsonObject();
		}
		result.put("data", res);
		return result.toJsonObject();
	}

}
